/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.ycl.data.exchange.runner.proxy;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.log4j.Logger;


public class HttpResponseParser {

    private static Logger logger = Logger.getLogger(HttpResponseParser.class);

    //返回内容
    public static String getResponseContent(HttpResponse response) {
        InputStream reponseStream = null;
        try {
            reponseStream = response.getEntity().getContent();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] bytesContent = new byte[1024];
            int bytesReadIn = 0;

            while ((bytesReadIn = reponseStream.read(bytesContent, 0, 1024)) > 0) {
                out.write(bytesContent, 0, bytesReadIn);
            }
            out.close();
            byte[] rep = out.toByteArray();

            return new String(rep, "UTF-8");
        } catch (Exception ex) {
            logger.error("write response content failed,cause " + ex.getMessage(), ex);
            return null;
        } finally {
            try {
                reponseStream.close();
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
    }

    //返回文件
    public static void getResponseFile(HttpResponse response, String filePath) {
        InputStream reponseStream = null;
        FileOutputStream fileout = null;
        try {
            reponseStream = response.getEntity().getContent();
            if (filePath == null) {
                filePath = getFilePath(response, filePath);
            }
            File file = new File(filePath);
            file.getParentFile().mkdirs();
            fileout = new FileOutputStream(file);

            int temp = 0;
            byte[] b = new byte[10240];
            while ((temp = reponseStream.read(b, 0, 10240)) != -1) {
                fileout.write(b, 0, temp);
            }
        } catch (Exception ex) {
            logger.error("write response file failed,cause " + ex.getMessage(), ex);
        } finally {
            try {
                if (reponseStream != null) {
                    reponseStream.close();
                }
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
            try {
                fileout.flush();
                if (fileout != null) {
                    fileout.close();
                }
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
    }

    //返回多个文件
    public static void getResponseFiles(HttpResponse response, String filePath) {
        InputStream reponseStream = null;
        FileOutputStream fileout = null;
        try {
            reponseStream = response.getEntity().getContent();
            String fileName = getFileName(response);
            filePath = filePath + "/" + fileName;
            System.out.println(filePath);
//            if (filePath == null) {
//                filePath = getFilePath(response, filePath);
//            }
            File file = new File(filePath);
            file.getParentFile().mkdirs();
            fileout = new FileOutputStream(file);

            int temp = 0;
            byte[] b = new byte[10240];
            while ((temp = reponseStream.read(b, 0, 10240)) != -1) {
                fileout.write(b, 0, temp);
            }
            System.out.println("fff");
        } catch (Exception ex) {
            logger.error("write response file failed,cause " + ex.getMessage(), ex);
        } finally {
//            try {
//                if (reponseStream != null) {
//                    reponseStream.close();
//                }
//            } catch (Exception ex) {
//                logger.error(ex.getMessage(), ex);
//            }
            try {
                fileout.flush();
                if (fileout != null) {
                    fileout.close();
                }
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
    }

    public static String getFilePath(HttpResponse response, String filepath) {
        if (!filepath.endsWith("/") || !filepath.endsWith("\\")) {
            filepath += "/";
        }
        String filename = getFileName(response);

        if (filename != null) {
            filepath += filename;
        } else {
            filepath += getRandomFileName();
        }
        return filepath;
    }

    public static String getFileName(HttpResponse response) {
        Header contentHeader = response.getFirstHeader("Content-Disposition");
        String filename = null;
        if (contentHeader != null) {
            HeaderElement[] values = contentHeader.getElements();
            if (values.length == 1) {
                NameValuePair param = values[0].getParameterByName("filename");
                if (param != null) {
                    try {
                        //filename = new String(param.getValue().toString().getBytes(), "utf-8");  
                        //filename=URLDecoder.decode(param.getValue(),"utf-8");  
                        filename = param.getValue();
                    } catch (Exception e) {
                        logger.error("gain response header failed,cause " + e.getMessage(), e);
                    }
                }
            }
        }
        return filename;
    }

    public static String getRandomFileName() {
        return String.valueOf(System.currentTimeMillis());
    }
}
